package com.algorithm.ch1.yjx.array;

import java.util.Arrays;

class RemoveDuplicates {
    public static void main(String[] args) {
        int[] nums = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4,4};
        int length = removeDuplicates2(nums);
        System.out.println("返回数组长度=" + length);
        System.out.println("处理后的原数组=" + Arrays.toString(nums));
        System.out.println("===最后结果===");
        for (int i = 0; i < length; i++) {
            System.out.println(nums[i]);
        }
    }

    //垃圾代码
    public static int removeDuplicates1(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        int maxNum = nums[nums.length - 1];
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                while (nums[i] == nums[j]) {
                    if (nums[i] == maxNum) {
                        return i + 1;
                    }
                    for (int k = j; k < nums.length - 1; k++) {
                        nums[k] = nums[k + 1];
                    }
                }
                break;
            }
        }
        return nums.length;
    }

    //最佳例子
    public static int removeDuplicates2(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        int index = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] != nums[index]) {
                index++;
                nums[index] = nums[i];
            }
        }
        return ++index;
    }


}